package controller;

import exception.LoginException;
import gui.OptionPane;

import java.rmi.RemoteException;

import model.UserInterface;
import rmi.client.ClientRemote;
import toolkit.Debug;
import rmi.client.Client;

public class Login extends Controller
{
	public Login()
	{
		setView(new view.Login(this));
	}
	
	public void login(String username, char[] password)
	{
		UserInterface user = null;
		
		if (username.isEmpty())
		{
			OptionPane.showError("Empty username", "Please fill in a username.");
		}
		else if (password.length == 0)
		{
			OptionPane.showError("Empty password", "Please fill in a password.");
		}
		else
		{
			try
			{
				user = userRemote.getUser(username, password);
				
				if (user != null)
				{
					ClientRemote client = new ClientRemote();
					client.setUser(user);
					
					serverRemote.addClient((Client) rmi.Client.toStub(client));
					
					setUser(user);
					setClient(client);
					
					forward(new controller.Lobby());
				}
				else
				{
					OptionPane.showError("Invalid input", "The username or/and the password are incorrect.");
				}
			}
			catch (LoginException e)
			{
				Debug.log(e);
				
				OptionPane.showError("Already logged in", "This user is already logged in.");
			}
			catch (RemoteException e)
			{
				Debug.log(e);
				
				OptionPane.showError("Error", "Something went wrong when trying to login.");
			}
		}
	}
	
	public void register()
	{
		forward(new controller.Register());
	}
}